package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.RedisConstants;
import com.ruoyi.common.constant.SqlConstants;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.system.domain.SystemConfig;
import com.ruoyi.system.mapper.SystemConfigMapper;
import com.ruoyi.system.service.ISystemConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author lixin
 * @date 2021-05-31 21:02
 */
@Service
public class SystemConfigServiceImpl extends ServicePlusImpl<SystemConfigMapper, SystemConfig> implements ISystemConfigService {

	@Autowired
	private RedisCache redisCache;

	@Override
	public SystemConfig getConfig() {
		// 优先从redis中获取
		SystemConfig systemConfig = redisCache.getCacheObject(RedisConstants.SYSTEM_CONFIG);
		if (ObjectUtil.isNull(systemConfig)) {
			LambdaQueryWrapper<SystemConfig> lqw = Wrappers.lambdaQuery();
			lqw.eq(SystemConfig::getStatus, SqlConstants.NORMAL);
			lqw.last(SqlConstants.LIMIT_ONE);
			systemConfig = this.getOne(lqw);
			if (ObjectUtil.isNull(systemConfig)) {
				throw new CustomException("系统配置不存在，请检查hy_system_config表是否有数据，并重新导入数据库");
			} else {
				// 将系统配置存入Redis中【设置过期时间24小时】
				redisCache.setCacheObject(RedisConstants.SYSTEM_CONFIG, systemConfig, 24, TimeUnit.HOURS);
			}

		}

		return systemConfig;
	}

	@Override
	public String cleanRedisByKey(List<String> key) {
		return null;
	}

	@Override
	public int editSystemConfig(SystemConfig systemConfigVo) {
		int row;
		if (StrUtil.isEmpty(StrUtil.toString(systemConfigVo.getConfigId()))) {
			// 新增
			row = baseMapper.insert(systemConfigVo);
		} else {
			// 修改
			SystemConfig systemConfig = baseMapper.selectById(systemConfigVo.getConfigId());
			BeanUtils.copyProperties(systemConfigVo, systemConfig);
			row = baseMapper.updateById(systemConfig);
		}

		// 更新系统配置成功后，需要删除Redis中的系统配置
		redisCache.deleteObject(RedisConstants.SYSTEM_CONFIG);
		return row;
	}
}
